package com.sr.examination.exam.exercise;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.sr.examination.R;
import com.sr.examination.common.event.CodeConstant;
import com.sr.examination.common.event.CollectionEvent;
import com.sr.examination.common.widget.ReaderViewPager;
import com.sr.examination.exam.common.PayModel;
import com.sr.examination.exam.common.widget.ExamMorePop;
import com.sr.examination.exam.exercise.category.CalculationFragment;
import com.sr.examination.exam.exercise.category.CaseAnalysisFragment;
import com.sr.examination.exam.exercise.category.ExerciseFragment;
import com.sr.examination.exam.exercise.category.InTrayFragment;
import com.sr.examination.exam.exercise.category.JudgementChoiceFragment;
import com.sr.examination.exam.exercise.category.MultipleChoiceFragment;
import com.sr.examination.exam.exercise.category.ShortAnswerFragment;
import com.sr.examination.exam.exercise.category.SingleChoiceFragment;
import com.sr.examination.exam.result.ResultActivity;
import com.sr.examination.net.Net;
import com.sr.examination.user.Account;
import com.tl.commonlibrary.event.EventUtil;
import com.tl.commonlibrary.network.ErrorResponse;
import com.tl.commonlibrary.network.RequestListener;
import com.tl.commonlibrary.network.bean.base.BaseBean;
import com.tl.commonlibrary.storage.configuration.PrefUtil;
import com.tl.commonlibrary.tool.Logger;
import com.tl.commonlibrary.tool.NumberUnit;
import com.tl.commonlibrary.tool.UIUtils;
import com.tl.commonlibrary.ui.BaseFragmentActivity;
import com.tl.commonlibrary.ui.beans.Answer;
import com.tl.commonlibrary.ui.beans.ExerciseBean;
import com.tl.commonlibrary.ui.beans.ExerciseListBean;
import com.tl.commonlibrary.ui.beans.SubjectiveScoreBean;
import com.tl.commonlibrary.ui.web.SoftHideKeyBoardUtil;
import com.tl.commonlibrary.ui.widget.CustomAlertDialog;
import com.tl.commonlibrary.ui.widget.TitleBar;

import java.util.ArrayList;
import java.util.List;

import retrofit2.Call;

/**
 * Created by jiangzhongshan on 18/2/3.
 * 进入答题练习
 */

public class ExerciseActivity extends BaseFragmentActivity {
    /**
     * 错题
     *
     * @param context
     * @param title
     * @param examId
     * @param pUserSummaryId
     */
    public static void startForWrongList(Context context, String title, long examId, int pUserSummaryId) {
        start(context, title, examId, ExerciseListBean.TYPE_WRONG_ANSWER, pUserSummaryId, null);
    }

    public static void start(Context context, String title, long examId, int type) {
        start(context, title, examId, type, null);
    }

    public static void start(Context context, String title, long examId, int type, ExerciseListBean exerciseListBean) {
        start(context, title, examId, type, Integer.MIN_VALUE, exerciseListBean);
    }

    public static void start(Context context, String title, long examId, int type, int pUserSummaryId, ExerciseListBean exerciseListBean) {
        if (Account.isLogged(context)) {
            Intent starter = new Intent(context, ExerciseActivity.class);
            starter.putExtra("examId", examId);
            starter.putExtra("title", title);
            starter.putExtra("type", type);
            if (pUserSummaryId >= 0) {
                starter.putExtra("pUserSummaryId", pUserSummaryId);
            }
            if (exerciseListBean != null) {
                starter.putExtra("ExerciseListBean", exerciseListBean);
            }
            context.startActivity(starter);
        }
    }

    public static void startForResult(Activity context, String title, long examId, int type, ExerciseListBean exerciseListBean, int requestCode) {
        if (Account.isLogged(context)) {
            Intent starter = new Intent(context, ExerciseActivity.class);
            starter.putExtra("examId", examId);
            starter.putExtra("title", title);
            starter.putExtra("type", type);
            if (exerciseListBean != null) {
                starter.putExtra("ExerciseListBean", exerciseListBean);
            }
            context.startActivityForResult(starter, requestCode);
        }
    }

    private ReaderViewPager exerciseViewPager;
    private View shadowView;
    private View centerProgressLayout, progressLayout, buttonLayout;
    private TextView ratioTView, centerRatioTView;
    private ProgressBar progressBar, centerProgressBar;
    private long examId;
    private int pUserSummaryId;
    private String title;
    private int type = ExerciseListBean.TYPE_TRAIL;
    private ExerciseListBean listBean;
    private ExerciseAdapter adapter;
    private ExerciseFragment[] fragmentList;
    private Button finishedOrAnalysisBtn, subjectiveScoreBtn;
    private View moreBtn;


    @Override

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.act_exercise);
        SoftHideKeyBoardUtil.assistActivity(this);
        exerciseViewPager = findViewById(R.id.exerciseViewPager);
        shadowView = findViewById(R.id.shadowView);
        findViewById(R.id.preItemBtn).setOnClickListener(this);
        findViewById(R.id.nextItemBtn).setOnClickListener(this);
        findViewById(R.id.numberCardBtn).setOnClickListener(this);
        centerProgressLayout = findViewById(R.id.centerProgressLayout);
        progressLayout = findViewById(R.id.progressLayout);
        buttonLayout = findViewById(R.id.buttonLayout);
        centerRatioTView = findViewById(R.id.centerRatioTView);
        centerProgressBar = findViewById(R.id.centerProgressBar);

        finishedOrAnalysisBtn = findViewById(R.id.finishedOrAnalysisBtn);
        subjectiveScoreBtn = findViewById(R.id.subjectiveScoreBtn);
        progressBar = findViewById(R.id.progressBar);
        ratioTView = findViewById(R.id.ratioTView);
        ratioTView.setText(getString(R.string.ratio_slash, 0, 0));
        title = getIntent().getStringExtra("title");
        examId = getIntent().getLongExtra("examId", -1);
        pUserSummaryId = getIntent().getIntExtra("pUserSummaryId", -1);
        type = getIntent().getIntExtra("type", ExerciseListBean.TYPE_TRAIL);
        listBean = (ExerciseListBean) getIntent().getSerializableExtra("ExerciseListBean");
        setTitle(title);
        if (listBean != null && listBean.hasExercise()) {
            init(0);
        } else {
            getExamList();
        }
    }

    private void init(int index) {
        initRightMenu();
        initButtonUI();
        fragmentList = new ExerciseFragment[listBean.getExerciseSize()];
        adapter = new ExerciseAdapter(getSupportFragmentManager());
        exerciseViewPager.setAdapter(adapter);
        exerciseViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                shadowView.setVisibility(View.VISIBLE);
                shadowView.setTranslationX(exerciseViewPager.getWidth() - positionOffsetPixels);
            }

            @Override
            public void onPageSelected(int position) {
                shadowView.setVisibility(View.GONE);
                updateProgress(position);
            }

            @Override
            public void onPageScrollStateChanged(int state) {
                Logger.i("", state + "");
            }
        });
        exerciseViewPager.setCurrentItem(index);
        if (listBean.isMethodPractice()) {
            finishedOrAnalysisBtn.setText(R.string.exercise_check_analysis);
        } else if (listBean.isMethodExamination()) {
            finishedOrAnalysisBtn.setText(R.string.exercise_hand_in);
        }
        finishedOrAnalysisBtn.setOnClickListener(this);
        subjectiveScoreBtn.setOnClickListener(this);
        progressBar.setMax(listBean.getExerciseSize());
        centerProgressBar.setMax(progressBar.getMax());
        updateProgress(index);
        //只有考试模式才会计时
        if (listBean.isMethodExamination() && type == ExerciseListBean.TYPE_ALL) {
            ExerciseListBean.startTime(context);
        }
        findViewById(R.id.containerLayout).setVisibility(View.VISIBLE);
    }

    private void initRightMenu() {
        if (moreBtn == null) {
            moreBtn = getTitleBar().addAction(new TitleBar.ImageAction(R.mipmap.ic_more) {
                @Override
                public void performAction(View view) {
                    showMore();
                }
            });
        }
    }

    private void updateProgress(int position) {
        String ratioStr = getString(R.string.ratio_slash, (position + 1), listBean.getExerciseSize());
        ratioTView.setText(ratioStr);
        progressBar.setProgress(position + 1);

        centerRatioTView.setText(ratioStr);
        centerProgressBar.setProgress(position + 1);
    }

    private void initButtonUI() {
        switch (type) {
            case ExerciseListBean.TYPE_ALL:
            case ExerciseListBean.TYPE_TRAIL:
                progressLayout.setVisibility(View.VISIBLE);
                centerProgressLayout.setVisibility(View.GONE);
                buttonLayout.setVisibility(View.VISIBLE);
                subjectiveScoreBtn.setVisibility(View.GONE);
                break;

            case ExerciseListBean.TYPE_COLLECTION:
            case ExerciseListBean.TYPE_WRONG_ANSWER:
            case ExerciseListBean.TYPE_EXERCISE_HISTORY:
                progressLayout.setVisibility(View.VISIBLE);
                centerProgressLayout.setVisibility(View.GONE);
                buttonLayout.setVisibility(View.VISIBLE);
                subjectiveScoreBtn.setVisibility(View.GONE);
                finishedOrAnalysisBtn.setVisibility(View.GONE);
                break;
            case ExerciseListBean.TYPE_RESULT_SUBJECTIVE_SCORE:
                progressLayout.setVisibility(View.VISIBLE);
                centerProgressLayout.setVisibility(View.GONE);
                buttonLayout.setVisibility(View.GONE);
                subjectiveScoreBtn.setVisibility(View.VISIBLE);
                break;
            case ExerciseListBean.TYPE_RESULT_ALL_ANALYSIS:
            case ExerciseListBean.TYPE_RESULT_WRONG_ANSWER_ANALYSIS:
            default:
                progressLayout.setVisibility(View.GONE);
                centerProgressLayout.setVisibility(View.VISIBLE);
                buttonLayout.setVisibility(View.GONE);
                subjectiveScoreBtn.setVisibility(View.GONE);
                break;

        }
    }

    private void getExamList() {
        findViewById(R.id.containerLayout).setVisibility(View.GONE);
        dismissNoData();
        showLoading();
        Call call = Net.getExerciseList(type, examId, pUserSummaryId, new RequestListener<BaseBean<ExerciseListBean>>() {
            @Override
            public void onSuccess(Call<BaseBean<ExerciseListBean>> call, BaseBean<ExerciseListBean> response) {
                if (response.isSuccessful()) {
                    listBean = response.data;
                    if (listBean != null && listBean.hasExercise()) {
                        Logger.e(tag, response.data.toString());
                        if (type == ExerciseListBean.TYPE_ALL) {
                            loadNativeResultIfNecessary();
                        } else {
                            init(0);
                            dismissLoading();
                        }
                    } else {
                        showNoDataView(getString(R.string.no_data_exam_list));
                        dismissLoading();
                    }
                } else {
                    dismissLoading();
                }
            }

            @Override
            public void onFailed(Call<BaseBean<ExerciseListBean>> call, ErrorResponse errorResponse) {
                dismissLoading();
            }
        });
        if (call == null) {
            dismissAll();
            showNoDataView();
        }
    }

    @Override
    public void onNoDataClicked() {
        super.onNoDataClicked();
        getExamList();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.preItemBtn://上一题
                previousItem();
                break;
            case R.id.nextItemBtn://下一题
                nextItem();
                break;
            case R.id.finishedOrAnalysisBtn://交卷或者查看解析
                saveCurrentExerciseInstanceState();
                finishedOrAnalysis();
                break;
            case R.id.numberCardBtn://题卡
                saveCurrentExerciseInstanceState();
                NumberCardActivity.start(this, listBean, title, examId, CodeConstant.EXERCISE_NUMBER_CARD);
                break;
            case R.id.subjectiveScoreBtn://提交全部自评分
                saveCurrentExerciseInstanceState();
                submitSubjectScoreDialog();
                break;

        }

    }

    /**
     * 保存当前fragment现场状态
     */
    private void saveCurrentExerciseInstanceState() {
        ExerciseFragment fragment = getCurrentExerciseFragment();
        if (fragment != null) {
            fragment.saveExerciseInstanceState();
        }
    }

    /**
     * 根据试卷模式判断当前是考试（交卷)还是练习(查看答案)
     */
    private void finishedOrAnalysis() {
        if (listBean.isMethodPractice()) {
            ExerciseFragment exerciseFragment = getCurrentExerciseFragment();
            if (exerciseFragment != null) {
                exerciseFragment.toExerciseModeAnalysis();
            }
        } else if (listBean.isMethodExamination()) {
//            //试用试卷需要购买
            if (showPay()) {
                return;
            }
            //交卷
            submitExercise();
        }
    }

    /**
     * 跳转到任意题
     *
     * @param position
     */
    public void item(int position) {
        if (position != exerciseViewPager.getCurrentItem() && position >= 0 && position < listBean.getExerciseSize()) {
            saveCurrentExerciseInstanceState();
            exerciseViewPager.setCurrentItem(position, Math.abs(exerciseViewPager.getCurrentItem() - position) == 1);
        }
    }

    /**
     * 返回上一题
     */
    public void previousItem() {
        int preItem = exerciseViewPager.getCurrentItem() - 1;
        if (preItem >= 0) {
            ExerciseFragment fragment = getCurrentExerciseFragment();
            if (fragment != null) {
                fragment.saveExerciseInstanceState();
            }
            exerciseViewPager.setCurrentItem(preItem, true);
        } else {
            //ouch!!! you are attaching my head!
            UIUtils.showToast(getString(R.string.exercise_no_more));
        }
    }

    /**
     * 进入下一题
     */
    public void nextItem() {
        saveCurrentExerciseInstanceState();
        int nextItem = exerciseViewPager.getCurrentItem() + 1;
        if (nextItem < listBean.getExerciseSize()) {
            exerciseViewPager.setCurrentItem(nextItem, true);
        } else {
            //all finished.
            if (listBean.isMethodExamination()) {
                if (showPay()) {
                    return;
                }
                //交卷
                submitExercise();
            } else {
                //ouch!!! you are attaching my head!
                UIUtils.showToast(getString(R.string.exercise_no_more));
            }
        }
    }

    @Override
    public void onFragmentTrigger(int tag, Bundle bundle) {
        if (tag == ExerciseBean.TYPE_SINGLE_CHOOSE) {
            exerciseViewPager.postDelayed(new Runnable() {
                @Override
                public void run() {
                    nextItem();
                }
            }, 300);
        }
    }

    private ExamMorePop examMorePop;

    /**
     * 更多 菜单
     */
    private void showMore() {
        if (examMorePop == null) {
            examMorePop = new ExamMorePop(this);
            examMorePop.setOnMoreListener(new ExamMorePop.OnMoreListener() {
                @Override
                public void onCollection() {
                    collection();
                }
            });
        }
        ExerciseBean exerciseBean = getCurrentExercise();
        if (exerciseBean != null) {
            examMorePop.setCollectionType(exerciseBean.getUserLike());
        }
        examMorePop.showAtLocation(getWindow().getDecorView(), Gravity.BOTTOM, 0, 0);
    }

    /**
     * 获取当前习题fragment
     *
     * @return
     */
    private ExerciseFragment getCurrentExerciseFragment() {
        int currItem = exerciseViewPager.getCurrentItem();
        return fragmentList[currItem];
    }

    /**
     * 获取当前习题数据
     *
     * @return
     */
    private ExerciseBean getCurrentExercise() {
        int pos = exerciseViewPager.getCurrentItem();
        if (listBean.getPaperItems() != null) {
            if (pos >= 0 && pos < listBean.getPaperItems().size()) {
                return listBean.getPaperItems().get(pos);
            }
        }
        return null;
    }

    private CustomAlertDialog submitDialog;
    private PayModel payModel;

    /**
     * 提交答案
     */
    private void submitExercise() {
        if (submitDialog == null) {
            submitDialog = new CustomAlertDialog(context);
            submitDialog.setContent(getString(R.string.dialog_submit_exercise));
            submitDialog.setLeftText(getString(R.string.submit_exercise_check_again));
            submitDialog.setRightText(getString(R.string.submit_exercise_submit));
            submitDialog.setListener(new CustomAlertDialog.OnAlertClickListener() {
                @Override
                public void onRightClicked(View view) {
                    ArrayList<Answer> answers = null;
                    if (listBean != null && listBean.getPaperItems() != null) {
                        ArrayList<ExerciseBean> exerciseBeans = listBean.getPaperItems();
                        if (!exerciseBeans.isEmpty()) {
                            Answer answer;
                            answers = new ArrayList<>();
                            for (ExerciseBean temp : exerciseBeans) {
                                if (temp != null) {
                                    if (temp.hasAnswer()) {
                                        answer = new Answer();
                                        answer.answer = temp.getUserAnswer();
                                        answer.itemId = temp.getItemId();
                                        answers.add(answer);
                                    }
                                }
                            }
                        }
                    }
                    if (answers != null) {
                        //只有考试模式才会计时
                        if (listBean.isMethodExamination() && type == ExerciseListBean.TYPE_ALL) {
                            ExerciseListBean.endTime(context);
                        }
                        showProgressDialog(getString(R.string.progress_submit_exercise), false);
                        Net.submitExercise(listBean.getpUserSummaryId(), answers, new RequestListener<BaseBean<ExerciseListBean>>() {
                            @Override
                            public void onSuccess(Call<BaseBean<ExerciseListBean>> call, BaseBean<ExerciseListBean> response) {
                                if (response.isSuccessful()) {
                                    ResultActivity.start(context, title, examId, response.data);
                                    finish();
                                }
                                dismissAll();
                            }

                            @Override
                            public void onFailed(Call<BaseBean<ExerciseListBean>> call, ErrorResponse errorResponse) {
                                dismissAll();
                            }
                        });
                    } else {
                        UIUtils.showToast(getString(R.string.hint_submit_exercise_exception));
                    }
                }

                @Override
                public void onLeftClicked(View view) {

                }
            });
        }
        submitDialog.show();
    }

    /**
     * 该试卷是否需要购买才能使用完整版本
     *
     * @return
     */
    private boolean showPay() {
        if (listBean.isStatusOnTrail()) {
            if (payModel == null) {
                payModel = new PayModel((BaseFragmentActivity) context);
                payModel.setListener(new PayModel.ExamPurchaseListener() {
                    @Override
                    public void purchaseSuccess() {
                        ExerciseActivity.start(context, title, examId, type);
                        finish();
                    }
                });
            }
            payModel.setPaperId(listBean.getPaperId());
            NumberUnit numberUnit = new NumberUnit(listBean.getPrice());
            payModel.show(numberUnit.setFormatDot(false).get2F());
            return true;
        }
        return false;
    }

    /**
     * 收藏，取消收藏
     */
    private void collection() {
        if (showPay()) {
            return;
        }
        if (getCurrentExercise() == null) {
            return;
        }
        showProgressDialog();
        final ExerciseBean cuurentExercise = getCurrentExercise();
        int action = 0;
        if (cuurentExercise.isUserUnLike()) {//未收藏去收藏
            action = 1;
        } else if (cuurentExercise.isUserLike()) {//已收藏去取消收藏
            action = 0;
        }
        Net.collection(action, listBean.getPaperId(), getCurrentExercise().getItemId(),
                new RequestListener<BaseBean>() {
                    @Override
                    public void onSuccess(Call<BaseBean> call, BaseBean response) {
                        if (response.isSuccessful()) {
                            cuurentExercise.resetUserLike();
                            if (cuurentExercise.isUserLike()) {
                                UIUtils.showToast(getString(R.string.collection_success));
                            } else if (cuurentExercise.isUserUnLike()) {
                                UIUtils.showToast(getString(R.string.un_collection_success));
                            }
                            EventUtil.post(new CollectionEvent(cuurentExercise.isUserLike() ? ExerciseBean.TYPE_COLLECTION : ExerciseBean.TYPE_UN_COLLECTION));
                        }
                        dismissProgressDialog();
                    }

                    @Override
                    public void onFailed(Call<BaseBean> call, ErrorResponse errorResponse) {
                        dismissProgressDialog();
                    }
                });
    }

    private CustomAlertDialog subjectScoreDialog;

    /**
     * 提交答案
     */
    private void submitSubjectScoreDialog() {
        if (subjectScoreDialog == null) {
            subjectScoreDialog = new CustomAlertDialog(context);
            subjectScoreDialog.setContent(getString(R.string.dialog_submit_subjective_score));
            subjectScoreDialog.setListener(new CustomAlertDialog.OnAlertClickListener() {
                @Override
                public void onRightClicked(View view) {
                    ArrayList<SubjectiveScoreBean> subjectiveScoreBeans = null;
                    if (listBean != null && listBean.getPaperItems() != null) {
                        ArrayList<ExerciseBean> exerciseBeans = listBean.getPaperItems();
                        if (!exerciseBeans.isEmpty()) {
                            subjectiveScoreBeans = new ArrayList<>();
                            SubjectiveScoreBean subjectiveScoreBean;
                            for (ExerciseBean temp : exerciseBeans) {
                                if (temp != null) {
                                    if (temp.isShortAnswer() && temp.hasMyScore()) {
                                        subjectiveScoreBean = new SubjectiveScoreBean();
                                        subjectiveScoreBean.itemId = temp.getItemId();
                                        subjectiveScoreBean.selfReportedScore = temp.getMyScore();
                                        subjectiveScoreBeans.add(subjectiveScoreBean);
                                    }
                                }
                            }
                        }
                    }
                    if (subjectiveScoreBeans != null) {
                        showProgressDialog(getString(R.string.progress_submit_subjective_score), false);
                        Net.submitSubjectiveScore(listBean.getpUserSummaryId(), examId, subjectiveScoreBeans, new RequestListener<BaseBean>() {
                            @Override
                            public void onSuccess(Call<BaseBean> call, BaseBean response) {
                                if (response.isSuccessful()) {
                                    Intent data = new Intent();
                                    data.putExtra("subjectiveBeans", listBean.getPaperItems());
                                    setResult(RESULT_OK, data);
                                    finish();
                                }
                                dismissAll();
                            }

                            @Override
                            public void onFailed(Call<BaseBean> call, ErrorResponse errorResponse) {
                                dismissAll();
                            }
                        });
                    } else {
                        UIUtils.showToast(getString(R.string.hint_submit_exercise_exception));
                    }
                }

                @Override
                public void onLeftClicked(View view) {

                }
            });
        }
        subjectScoreDialog.show();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case CodeConstant.EXERCISE_NUMBER_CARD:
                if (resultCode == RESULT_OK) {
                    if (data != null) {
                        boolean finish = data.getBooleanExtra("finish", false);
                        if (finish) {
                            finish();
                            return;
                        }
                        int numberCard = data.getIntExtra("NumberCard", -1);
                        if (numberCard != -1) {
                            numberCard -= 1;
                            if (numberCard >= 0 && numberCard < listBean.getExerciseSize()) {
                                item(numberCard);
                            }
                        }
                    }
                }
                break;
        }
    }

    private CustomAlertDialog exitDialog;

    private void showExitDialog() {
        if (exitDialog == null) {
            exitDialog = new CustomAlertDialog(context);
            exitDialog.setContent("确定退出吗?");
            exitDialog.setListener(new CustomAlertDialog.OnAlertClickListener() {
                @Override
                public void onRightClicked(View view) {
                    saveCurrentExerciseInstanceState();
                    saveResult();
                    finish();
                }

                @Override
                public void onLeftClicked(View view) {

                }
            });
        }
        exitDialog.show();
    }

    @Override
    public void back() {
        showExitDialog();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            back();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (examMorePop != null) {
            examMorePop.dismiss();
            examMorePop.setOnMoreListener(null);
            examMorePop = null;
        }
        if (payModel != null) {
            payModel.onDestroy();
            payModel = null;
        }
        if (submitDialog != null) {
            submitDialog.dismiss();
            submitDialog = null;
        }
        if (subjectScoreDialog != null) {
            subjectScoreDialog.dismiss();
            subjectScoreDialog = null;
        }
        if (exitDialog != null && exitDialog.isShowing()) {
            exitDialog.dismiss();
        }
        exitDialog = null;
    }


    private Handler loadNativeResultHandler = new Handler() {
        @Override
        public void handleMessage(Message message) {
            if (message != null) {
                if (message.arg1 == 100) {
                    init((Integer) message.obj);
                    dismissLoading();
                }
            }
            super.handleMessage(message);
        }

    };

    /**
     * 退出时，保存答题结果,只保留最后一次的答题结果
     * 只保存考试和模拟的，其他情况不保存
     */
    private void saveResult() {
        if (type == ExerciseListBean.TYPE_ALL && listBean != null) {
            ArrayList<ExerciseBean> items = listBean.getPaperItems();
            if (items != null && !items.isEmpty()) {
                int currentIndex = exerciseViewPager.getCurrentItem();
                PrefUtil prefUtil = new PrefUtil(context, "saveExercise");
                prefUtil.removeAll();
                prefUtil.putLong("saveExerciseId", examId);
                prefUtil.putInt("saveExerciseIndex", currentIndex);
                prefUtil.putString("saveExerciseItems", new Gson().toJson(items));
            }

        }
    }

    /**
     * 取出结果，如果当前考试练习结果已保存
     */
    private void loadNativeResultIfNecessary() {
        if (listBean != null) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    int nativeCurrentIndex = 0;
                    ArrayList<ExerciseBean> currentExerciseBeans = listBean.getPaperItems();
                    if (currentExerciseBeans != null && !currentExerciseBeans.isEmpty()) {
                        PrefUtil prefUtil = new PrefUtil(context, "saveExercise");
                        long nativeExamId = prefUtil.getLong("saveExerciseId", -1);
                        if (nativeExamId == examId) {
                            nativeCurrentIndex = prefUtil.getInt("saveExerciseIndex", 0);
                            String nativeResultItems = prefUtil.getString("saveExerciseItems", "");
                            List<ExerciseBean> nativeExerciseBeans = new Gson().fromJson(nativeResultItems, new TypeToken<List<ExerciseBean>>() {
                            }.getType());
                            if (nativeExerciseBeans != null) {
                                ExerciseBean currBean, nativeBean;
                                String result = null;
                                for (int i = 0; i < currentExerciseBeans.size(); i++) {
                                    currBean = currentExerciseBeans.get(i);
                                    for (int j = 0; j < nativeExerciseBeans.size(); j++) {
                                        nativeBean = nativeExerciseBeans.get(j);
                                        if (currBean.getItemId() == nativeBean.getItemId()) {
                                            result = nativeBean.getUserAnswer();
                                            if (!TextUtils.isEmpty(result)) {
                                                currBean.setUserAnswer(nativeBean.getUserAnswer());
                                            }
                                            nativeExerciseBeans.remove(j);
                                            break;
                                        }
                                    }
                                }
                            }
                            prefUtil.removeAll();
                        }
                    }
                    Message message = Message.obtain();
                    message.obj = nativeCurrentIndex;
                    message.arg1 = 100;
                    loadNativeResultHandler.sendMessage(message);
                }

            }).start();
        } else {
            Message message = Message.obtain();
            message.obj = 0;
            message.arg1 = 100;
            loadNativeResultHandler.sendMessage(message);
        }
    }

    /**
     * *********************************************************************************************************************************************************************
     * *********************************************************************************************************************************************************************
     */
    private class ExerciseAdapter extends FragmentPagerAdapter {

        public ExerciseAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            ExerciseFragment fragment = (ExerciseFragment) super.instantiateItem(container, position);
            ExerciseBean exerciseBean = listBean.getPaperItems().get(position);
            //查看历史考试，直接使用解析模式
            if (type == ExerciseListBean.TYPE_EXERCISE_HISTORY) {
                exerciseBean.setDisplayMode(ExerciseBean.DISPLAY_MODE_ANALYSIS);
            }
            fragment.setExerciseBean(exerciseBean);
            if (fragmentList != null) {
                fragmentList[position] = fragment;
            }
            return fragment;
        }

        @Override
        public int getItemPosition(Object object) {
//            return super.getItemPosition(object);
            return PagerAdapter.POSITION_NONE;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            super.destroyItem(container, position, object);
            fragmentList[position] = null;
        }

        @Override
        public Fragment getItem(int position) {
            ExerciseBean exerciseBean = listBean.getPaperItems().get(position);
            //单选题
            if (exerciseBean.isSingleChoose()) {
                return SingleChoiceFragment.newInstance(exerciseBean, listBean.getMethod());
            }
            //多选题
            if (exerciseBean.isMultipleChoose()) {
                return MultipleChoiceFragment.newInstance(exerciseBean, listBean.getMethod());
            }
            //判断题
            if (exerciseBean.isJudgementChoose()) {
                return JudgementChoiceFragment.newInstance(exerciseBean, listBean.getMethod());
            }
            //简答题
            if (exerciseBean.isShortAnswer()) {
                return ShortAnswerFragment.newInstance(exerciseBean, listBean.getMethod());
            }
            //案例分析题
            if (exerciseBean.isCaseAnalysis()) {
                return CaseAnalysisFragment.newInstance(exerciseBean, listBean.getMethod());
            }
            //计算题
            if (exerciseBean.isCalculation()) {
                return CalculationFragment.newInstance(exerciseBean, listBean.getMethod());
            }
            //文筐测验题
            if (exerciseBean.isInTray()) {
                return InTrayFragment.newInstance(exerciseBean, listBean.getMethod());
            }
            return SingleChoiceFragment.newInstance(exerciseBean, listBean.getMethod());
        }

        @Override
        public int getCount() {
            return listBean.getExerciseSize();
        }

    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            hiddenKeyboard();
        }
        return super.dispatchTouchEvent(ev);
    }
}
